import { Form, Input, Button, Divider, App, Checkbox } from 'antd'
import { PageContainer } from '@ant-design/pro-components'
import { useModel } from '@umijs/max'
import { useEffect, useState } from 'react'
import styles from './BaseSet.less'
import FormUploadImg from '@/components/FormUploadImg'

const formItemLayout = {
  labelCol: { span: 2 },
  wrapperCol: { span: 10 }
}

const BaseSet = () => {
  const [formRef] = Form.useForm()
  const { GetBaseInfo, UpdateBaseInfo } = useModel('BaseSet')
  const { contentWidth } = useModel('Global')
  const { message, modal } = App.useApp()

  const [formDisabled, setFormDisabled] = useState(true)

  const handleAddAndEditOk = async type => {
    if (type === 'edit') {
      setFormDisabled(false)
    } else if (type === 'save') {
      await formRef.validateFields()
      const values = formRef.getFieldsValue()
      // console.log('values========', values)

      const { is_phone, is_pic } = values
      // is_phone 和 is_pic 至少有一个为true
      if (!is_phone && !is_pic) {
        modal.warning({
          title: '客服配置功能缺失',
          content: '为保证客服功能正常，请至少需要勾选一项客服配置。'
        })
        return
      }

      let params = {
        ...values,
        is_phone: is_phone ? 1 : 0,
        is_pic: is_pic ? 1 : 0
      }

      const res = await UpdateBaseInfo(params)
      if (res) {
        setFormDisabled(true)
        message.success('保存成功')
        GetBaseSetData()
      }
    }
  }

  const handleCancel = () => {
    setFormDisabled(true)
    GetBaseSetData()
  }

  const GetBaseSetData = async () => {
    const res = await GetBaseInfo()
    if (res) {
      formRef.setFieldsValue({
        ...res
      })
    }
  }

  useEffect(() => {
    GetBaseSetData()
  }, [])

  useEffect(() => {
    document.getElementsByClassName('ant-page-header')[0].style.width = `${contentWidth}px`
  }, [contentWidth])

  const formatExtra = () => {
    return formDisabled
      ? [
          <Button key='edit' type='primary' onClick={() => handleAddAndEditOk('edit')}>
            编辑
          </Button>
        ]
      : [
          <Button key='cancel' onClick={() => handleCancel()}>
            取消
          </Button>,
          <Button key='submit' type='primary' onClick={() => handleAddAndEditOk('save')}>
            保存
          </Button>
        ]
  }

  return (
    <div className={styles.page_wrapper}>
      <PageContainer
        header={{
          fixedHeader: true,
          title: (
            <div className={styles.header_title}>
              <span>客服配置</span>
              <Divider type='vertical' />
              <span className={styles.header_desc}>基础配置页</span>
            </div>
          ),
          extra: formatExtra()
        }}
      >
        <div className={styles.wrapper}>
          <Form form={formRef} name='form_modal' disabled={formDisabled}>
            {/* 客服电话 */}
            <Form.Item name='is_phone' valuePropName='checked' label='' colon>
              <Checkbox>直接拨打客服电话（可以直接拨打电话联系客服，需设置联系电话）</Checkbox>
            </Form.Item>
            <Form.Item shouldUpdate={(prevValues, curValues) => prevValues.is_phone !== curValues.is_phone}>
              {() => {
                let disabledInput = formRef.getFieldValue('is_phone') && !formDisabled
                return (
                  <>
                    <Form.Item
                      {...formItemLayout}
                      name='contract_phone'
                      label='客服电话 : '
                      rules={[
                        {
                          required: disabledInput,
                          message: '请输入客服电话'
                        }
                      ]}
                    >
                      <Input placeholder='请输入' allowClear disabled={!disabledInput} />
                    </Form.Item>
                  </>
                )
              }}
            </Form.Item>

            {/* 客服微信 */}
            <Form.Item name='is_pic' valuePropName='checked' label='' colon>
              <Checkbox>添加客服联系方式（支持上传图片、公众号二维码等）</Checkbox>
            </Form.Item>

            <Form.Item shouldUpdate={(prevValues, curValues) => prevValues.is_pic !== curValues.is_pic}>
              {() => {
                let disabledInput = formRef.getFieldValue('is_pic') && !formDisabled
                return (
                  <FormUploadImg
                    {...formItemLayout}
                    required={disabledInput}
                    name='contract_pic'
                    label='客服联系方式'
                    disabled={!disabledInput}
                    text='上传图片'
                    extra='建议图片比例为正方形'
                  />
                )
              }}
            </Form.Item>
            <Form.Item {...formItemLayout} name='remark' label='提示文字' extra='提示文字显示在图片下方，20字以内'>
              <Input placeholder='请输入' allowClear />
            </Form.Item>
          </Form>
        </div>
      </PageContainer>
    </div>
  )
}

export default BaseSet
